package itsm.isperp.module.controller.change;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseProcessController;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.change.ChgChange;
import itsm.isperp.module.entity.change.ChgElementRelation;
import itsm.isperp.module.entity.change.ChgRiskElement;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.change.ChgChangeService;
import itsm.isperp.module.service.change.ChgElementRelationService;
import itsm.isperp.module.service.change.ChgRiskElementService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.project.ProjProjectService;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-7-18
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("change/change")
public class ChgChangeController extends BaseProcessController<ChgChange> {

	@Autowired
	protected ChgChangeService chgChangeService;

	@Autowired
	protected AppDictService appDictService;

	@Autowired
	protected ProjProjectService projProjectService;

	@Override
	public String getProceessKey() {
		return "changeProcess";
	}

	@Override
	public ChgChangeService getService() {
		return chgChangeService;
	}

	@Override
	public String getPageTitle() {
		return "变更";
	}

	@RequestMapping("newChangeEdit")
	public ModelAndView newChangeEdit(String id, HttpServletRequest req) throws Exception {
		ModelAndView mv = new ModelAndView("change/change/newChangeEdit");

		ChgChange model = null;
		IUser user = ContextHolder.getLoginUser();
		if (StringUtils.isEmpty(id)) {
			model = new ChgChange();
			model.setId(HibernateUUIDGenerator.generate());

			model.setRequester(user.getUsername());
			model.setRequesterName(user.getFullname());
			model.setRequestDate(new Timestamp(new Date().getTime()));

		} else {
			model = this.getService().findOne(id);
			mv.addObject("modelEdit", true);

			ConfCiService confCiService = ContextHolder.getSpringBean("confCiService");

			Map<String, Object> ci = confCiService.findOneToMap(model.getCiId(), "name");

			if (MapUtils.isNotEmpty(ci))
				mv.addObject("ciName", ci.get("name"));

		}

		mv.addObject("currentUserId", user.getUsername());
		mv.addObject("currentUserName", user.getFullname());

		if (StringUtils.isEmpty(model.getSupporter())) {
			model.setSupporter(user.getUsername());
			model.setSupporterName(user.getFullname());
		}

		mv.addObject("model", model);

		List<AppDict> types = this.appDictService.findByType("CHANGE_TYPE");
		// 风险
		List<AppDict> riskRanks = this.appDictService.findByType("CHANGE_RISKRANK");

		// 紧急
		List<AppDict> urgencys = this.appDictService.findByType("CHANGE_URGENCY");

		// 影响
		List<AppDict> effects = this.appDictService.findByType("CHANGE_EFFECT");
		// 级别
		List<AppDict> prioritys = this.appDictService.findByType("CHANGE_PRIORITY");

		List<ProjProject> projects = this.projProjectService.findAllPublished("id", "name");

		mv.addObject("types", types);
		mv.addObject("riskRanks", riskRanks);
		mv.addObject("urgencys", urgencys);
		mv.addObject("effects", effects);
		mv.addObject("prioritys", prioritys);
		mv.addObject("projects", projects);

		return mv;
	}

	@RequestMapping("changeHandleEdit")
	public ModelAndView changeHandleEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("change/change/changeHandleEdit");

		ChgChange model = this.getService().findOne(id);
		if(StringUtils.isEmpty(model.getExecuter()))
		{
			IUser user = ContextHolder.getLoginUser();
			model.setExecuter(user.getUsername());
			model.setExecuterName(user.getFullname());
		}
		mv.addObject("model", model);
		JqGridRequest request=new JqGridRequest();
		mv.addObject("risk_category",
				appDictService.findByType("CHANGE_RISK_CATEGORY"));
		request.setSort("order_num", Direction.DESC);
		ChgRiskElementService chgRiskElementService = ContextHolder
				.getSpringBean("chgRiskElementService");
		PageResponse<ChgRiskElement> list=chgRiskElementService.findAll(request).toPage();
		mv.addObject("risk_elementlist",list); 

		return mv;

	}

	@RequestMapping("changeEvaluateEdit")
	public ModelAndView changeEvaluateEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("change/change/changeEvaluateEdit");

		ChgChange model = this.getService().findOne(id);
		mv.addObject("model", model);
		JqGridRequest request=new JqGridRequest();
		mv.addObject("risk_category",
				appDictService.findByType("CHANGE_RISK_CATEGORY"));
		request.setSort("order_num", Direction.DESC);
		ChgRiskElementService chgRiskElementService = ContextHolder
				.getSpringBean("chgRiskElementService");
		PageResponse<ChgRiskElement> list=chgRiskElementService.findAll(request).toPage();
		mv.addObject("risk_elementlist",list); 

		return mv;

	}

	@RequestMapping("view")
	@Override
	public ModelAndView view(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("change/change/view");

		ChgChange model = this.getService().findOne(id);
		mv.addObject("model", model);
		JqGridRequest request=new JqGridRequest();
		mv.addObject("risk_category",
				appDictService.findByType("CHANGE_RISK_CATEGORY"));
		request.setSort("order_num", Direction.DESC);
		ChgRiskElementService chgRiskElementService = ContextHolder
				.getSpringBean("chgRiskElementService");
		PageResponse<ChgRiskElement> list=chgRiskElementService.findAll(request).toPage();
		mv.addObject("risk_elementlist",list); 
		return mv; 
	}

	@RequestMapping("approvalEdit")
	public ModelAndView approvalEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("change/change/approvalEdit");

		ChgChange model = this.getService().findOne(id);
		mv.addObject("model", model);
		JqGridRequest request=new JqGridRequest();
		mv.addObject("risk_category",
				appDictService.findByType("CHANGE_RISK_CATEGORY"));
		request.setSort("order_num", Direction.DESC);
		ChgRiskElementService chgRiskElementService = ContextHolder
				.getSpringBean("chgRiskElementService");
		PageResponse<ChgRiskElement> list=chgRiskElementService.findAll(request).toPage();
		mv.addObject("risk_elementlist",list); 
		List<AppDict> types = this.appDictService.findByType("CHANGE_TYPE");
		mv.addObject("types",types); 
		return mv;

	}
	
	@RequestMapping("changePlanEdit")
	public ModelAndView changePlanEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("change/change/changePlanEdit");

		ChgChange model = this.getService().findOne(id);
		mv.addObject("model", model);
		JqGridRequest request=new JqGridRequest();
		mv.addObject("risk_category",
				appDictService.findByType("CHANGE_RISK_CATEGORY"));
		request.setSort("order_num", Direction.DESC);
		ChgRiskElementService chgRiskElementService = ContextHolder
				.getSpringBean("chgRiskElementService");
		PageResponse<ChgRiskElement> list=chgRiskElementService.findAll(request).toPage();
		mv.addObject("risk_elementlist",list); 
		List<AppDict> types = this.appDictService.findByType("CHANGE_TYPE");
		mv.addObject("types",types); 
		return mv;

	}
	
	@RequestMapping("approvalEdit2")
	public ModelAndView approvalEdit2(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("change/change/approvalEdit2");

		ChgChange model = this.getService().findOne(id);
		mv.addObject("model", model);
		JqGridRequest request=new JqGridRequest();
		mv.addObject("risk_category",
				appDictService.findByType("CHANGE_RISK_CATEGORY"));
		request.setSort("order_num", Direction.DESC);
		ChgRiskElementService chgRiskElementService = ContextHolder
				.getSpringBean("chgRiskElementService");
		PageResponse<ChgRiskElement> list=chgRiskElementService.findAll(request).toPage();
		mv.addObject("risk_elementlist",list); 
		List<AppDict> types = this.appDictService.findByType("CHANGE_TYPE");
		mv.addObject("types",types); 
		return mv;

	}

	@RequestMapping("statusProcessManage")
	public ModelAndView statusProcessManage() {
		return this.getModelAndView();
	}

	@RequestMapping("statusProcessMenu")
	@ResponseBody
	public ITreeNode[] statusProcessMenu() {
		return this.createStatusProcessCountQuery().getTreeNodes();

	}

	protected CountQuery createStatusProcessCountQuery() {
		CountQuery cq = this.createDefaultCountQuery();

		List<AppDict> dicts = this.appDictService.findByType("CHANGE_STATUS");

		for (AppDict d : dicts) {
			cq.addCountFilter(d.getName(), true, " a.status='" + d.getName() + "' ");
		}

		return cq;
	}

	@RequestMapping("listStatusProcessDetail")
	@ResponseBody
	public PageResponse<Map<String, Object>> listStatusProcessDetail(JqGridRequest request, HttpServletRequest req) {
		return this.getListDetail(createStatusProcessCountQuery(), request, req);
	}

	/**
	 * 向导式创建页面
	 * 
	 * @param req
	 *            http请求
	 * @return 向导式创建页面
	 */
	@RequestMapping("wizCreateEdit")
	public ModelAndView wizCreateEdit(String id, HttpServletRequest req) {
		ChgChange model = null;
		ModelAndView mv = new ModelAndView("change/change/wizCreateEdit");
		mv.addObject("id", HibernateUUIDGenerator.generate());
		IUser user = ContextHolder.getLoginUser();
		mv.addObject("currentUserId", user.getUsername());
		mv.addObject("currentUserName", user.getFullname());

		if (StringUtils.isEmpty(id)) {
			model = new ChgChange();
			model.setId(HibernateUUIDGenerator.generate());

			model.setRequester(user.getUsername());
			model.setRequesterName(user.getFullname());
			model.setRequestDate(new Timestamp(new Date().getTime()));

		} else {
			model = this.getService().findOne(id);

			mv.addObject("modelEdit", true);
		}
		JqGridRequest request = new JqGridRequest();
		mv.addObject("risk_category", appDictService.findByType("CHANGE_RISK_CATEGORY"));
		request.setSort("order_num", Direction.DESC);
		ChgRiskElementService chgRiskElementService = ContextHolder.getSpringBean("chgRiskElementService");
		PageResponse<ChgRiskElement> list = chgRiskElementService.findAll(request).toPage();
		mv.addObject("risk_elementlist", list);

		mv.addObject("currentUserId", user.getUsername());
		mv.addObject("currentUserName", user.getFullname());

		/*
		 * if (StringUtils.isEmpty(model.getSupporterId())) {
		 * model.setSupporterId(user.getUsername());
		 * model.setSupporterName(user.getFullname()); }
		 */
		mv.addObject("model", model);
		List<AppDict> types = this.appDictService.findByType("CHANGE_TYPE");
		// 风险
		List<AppDict> riskRanks = this.appDictService.findByType("CHANGE_RISKRANK");
		mv.addObject("types", types);
		mv.addObject("riskRanks", riskRanks);

		// 级别
		List<AppDict> prioritys = this.appDictService.findByType("CHANGE_PRIORITY");
		mv.addObject("prioritys", prioritys);
		
		List<ProjProject> projects = this.projProjectService.findAllPublished("id", "name");
		mv.addObject("projects", projects);
		return mv;

	}

	@RequestMapping("chgConfigurationEdit")
	@ResponseBody
	public ModelAndView chgConfigurationEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String changeId = request.getParameter("changeId");
		String ciId = request.getParameter("id");
		String tecServiceId = request.getParameter("tecServiceId");
		ConfCiService confCiService = ContextHolder.getSpringBean("confCiService");
		ConfCi ci = confCiService.findOne(ciId);
		ModelAndView mv = new ModelAndView("change/change/chgConfigurationEdit");
		mv.addObject("model", ci);
		mv.addObject("changeId", changeId);
		mv.addObject("tecServiceId", tecServiceId);
		return mv;
	}
	@RequestMapping("updateChgElementRelation")
	@ResponseBody
	public ResultMessage updateChgElementRelation(HttpServletRequest req) {
		String sourceId = req.getParameter("id");
		String toIds = req.getParameter("tids");
		String toType = req.getParameter("ty");
		if (StringUtils.isNotEmpty(sourceId) && StringUtils.isNotEmpty(toIds)) {
			ChgElementRelationService chgElementRelationService = ContextHolder.getSpringBean("chgElementRelationService");
			chgElementRelationService.deleteAllByfromId(sourceId,toType);
			String[] toIdsArr = toIds.split(",");
			for (String id : toIdsArr) {
				ChgElementRelation cr = new ChgElementRelation();
				cr.setFromId(sourceId);
				cr.setToId(id);
				cr.setToType(toType);
				chgElementRelationService.saveOrUpdate(cr);
			}
			return new ResultMessage(true, "ok");
		} else {
			return new ResultMessage(false, "err");
		}
	}
	
	@RequestMapping("changeCloseEdit")
	public ModelAndView changeCloseEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("change/change/changeCloseEdit");

		ChgChange model = this.getService().findOne(id);
		mv.addObject("model", model);
		return mv;

	}
}
